﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime;
using System.Runtime.Caching;
using System.Collections;
/*
.NET 4.0后支持的内存缓存
*/
namespace IHISCETeim.Library
{
    public class Caching4Strategy : ICacheStrategy
    {
        private static readonly Object _locker = new object();

        protected int _timeOut = 1440;
        public virtual int TimeOut
        {
            set { _timeOut = value > 0 ? value : 6000; }
            get { return _timeOut > 0 ? _timeOut : 6000; }
        }

        public void Add(string CacheKey, object o)
        {
            Add(CacheKey, o, TimeOut);
        }

        public void Add(string CacheKey, object o, string[] dependKey)
        {
             Add( CacheKey,  o, TimeOut);
        }

        public void Add(string CacheKey, object o, int timeoutminute)
        {
            Add2(CacheKey, 0, timeoutminute);
        }

        public  void Add2(string CacheKey, object o, int timeoutminute)
        {
            if (String.IsNullOrWhiteSpace(CacheKey)) throw new ArgumentException("Invalid cache key");
            if (o == null) throw new ArgumentNullException("cachePopulate");
            //   if (slidingExpiration == null && absoluteExpiration == null) throw new ArgumentException("Either a sliding expiration or absolute must be provided");
            TimeSpan slidingExpiration = new TimeSpan(timeoutminute*100*60);

            if (MemoryCache.Default[CacheKey] == null)
            {
                lock (_locker)
                {
                    if (MemoryCache.Default[CacheKey] == null)
                    {
                        var item = new CacheItem(CacheKey, o);
                        var policy = CreatePolicy(slidingExpiration,null);

                        MemoryCache.Default.Add(item, policy);
                    }
                }
            }

           // return MemoryCache.Default[CacheKey];
        }
        private static  CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
        {
            var policy = new CacheItemPolicy();

            if (absoluteExpiration.HasValue)
            {
                policy.AbsoluteExpiration = absoluteExpiration.Value;
            }
            else if (slidingExpiration.HasValue)
            {
                policy.SlidingExpiration = slidingExpiration.Value;
            }

            policy.Priority = CacheItemPriority.Default;

            return policy;

        }

        public bool Clear()
        {
           
            return true;
        }

        public object Get(string CacheKey)
        {
            return MemoryCache.Default[CacheKey];
        }

        public void Remove(string CacheKey)
        {
            MemoryCache.Default.Remove(CacheKey);
        }

       
    }

}
